const jwt = require("jsonwebtoken");
const { generatorToken, SECRET } = require("./utils");

const login = {
  methods: "post",
  handle: (req, res) => {
    const { token, refreshToken } = generatorToken();
    res.send({
      msg: "请求成功",
      success: true,
      status: 200,
      response: {
        token,
        refreshToken,
      },
    });
  },
};
const refreshToken = {
  methods: "post",
  handle: (req, res) => {
    const refreshToken = req.body.refreshToken;
    try {
      jwt.verify(refreshToken, SECRET);
      const { token: newToken, refreshToken: newRefreshToken } =
        generatorToken();
      res.send({
        msg: "请求成功",
        success: true,
        status: 200,
        response: {
          token: newToken,
          refreshToken: newRefreshToken,
        },
      });
    } catch (e) {
      console.log(e);
      res.status(500).send({
        msg: "refreshToken已过期",
        success: true,
        status: 500,
        response: null,
      });
    }
  },
};

module.exports = {
  login,
  refreshToken,
};
